<?php
/*
 * @Author: 李明
 * @Date: 2021-08-22 14:45:17
 * @LastEditors: 李明
 * @LastEditTime: 2022-01-17 14:56:38
 * @Description: file content
 */

namespace App\Http\Controllers\admin;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils;
use App\Http\Resources\Worker as ResourcesWorker;
use App\Models\Branch;
use App\Models\Role;
use App\Models\SystemBase;
use App\Models\SystemRecord;
use App\Models\User;
use App\Models\UserWorker;
use App\Models\WorkerBranch;
use App\Models\Worker;
use App\Models\WorkerRole;
use Illuminate\Http\Request;

class WorkerController extends Controller
{

    /**
     * @description: 员工编辑添加借口
     * @param {Request} $request
     * @return {*}
     */
    public function newWorkerSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // 接参
        try {
            $all = $request->all();
            $phoneNum = $all['phoneNum'];
            $is_change = isset($all['id']);
            $worker_list = Worker::where("phoneNum", $phoneNum)->get();
            if ($is_change) { // 如果是修改，需要先判断 是否已存在一样的账号
                if (count($worker_list) == 1) {
                    if ($worker_list[0]->id != $all['id']) {
                        return LMReturn::Error('存在重复账号，禁止修改', 'WCNWS1');
                    }
                } elseif (count($worker_list) > 1) {
                    return LMReturn::Error('不应该出现这种问题', 'WCNWS2');
                }
            } else { // 如果是增加，需要先判断 是否已存在该账号
                if (count($worker_list) > 0) {
                    return LMReturn::Error('账号已存在', 'WC009');
                }
            }
            $worker = $is_change ? Worker::find($all['id']) : new Worker();
            $role_list = [$all['roleinfo']];
            $branch_list = [$all['bminfo']];
            $id_type = isset($all['id_type']) ? $all['id_type'] : '1';
            $inTime = $all['inTime'];
            $id_number = isset($all['id_number']) ? $all['id_number'] : '';
            $sex = $all['sex'];
            $birthday = isset($all['birthday']) ? $all['birthday'] : '';
            $password = $is_change ? $worker->password : CommonFun::md5($all['password']);
            $contactNum = $all['contactNum'];
            $name = $all['name'];
            $user_status = isset($all['user_status']) ? $all['user_status'] : 1;
            $manage_branch_list = $all['manage_bm'] ?? [];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参失败', 'WC014');
        }
        // 修改数据库
        try {
            $worker->name = $name;
            $worker->phoneNum = $phoneNum;
            $worker->contactNum = $contactNum;
            $worker->inTime = $inTime;
            $worker->sex = $sex;
            $worker->id_type = $id_type;
            $worker->id_number = $id_number;
            $worker->password = $password;
            $worker->user_status = $user_status;
            $worker->birthday = $birthday;
            $worker->account_status = 1;
            $worker->save();
            $worker->refresh();
            $worker->roles()->sync($role_list); // 替换之前的角色。
            $worker->branches()->sync($branch_list); // 替换之前的关联部门。
            $worker->branchesManage()->sync($manage_branch_list); // 替换之前的管理部门。
            // 替换之前的用户的部门跟随客户经理变动归属部门
            if ($is_change) {
                User::where('worker_id', $all['id'])->update(['branch_id' => $all['bminfo']]);
            }
            return LMReturn::Success($worker, $is_change ? '修改员工成功' : '添加员工成功');
        } catch (\Throwable $th) {
            return LMReturn::Error($is_change ? '修改员工失败' : '添加员工失败', 'WC011');
        }
    }

    /**
     * @description: 员工列表
     * @param {*}
     * @return {*}
     */
    public function WorkerList(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            //接收前端传递过来的值
            $all = $request->all();
            $pageSize = $all['size'] ?? 15;
            $worker_id = $tokenInfo['worker_id'];
            $where = [];
            $where[] = ['worker.account_status', '!=', '3'];
            if (isset($all['worker_name'])) {
                $where[] = ['worker.name', 'like', '%' . $all['worker_name'] . '%'];
            }
            if (isset($all['branch_id'])) { // 管理部门和部门二选一（都传取branch_id），传管理部门是全部，传部门是部门下的数据
                $where[] = ['branch.id', $all['branch_id']];
            }
            if (isset($all['worker.user_status'])) { // 1是在职 0是离职  2待入职
                $where[] = ['worker.user_status', $all['user_status']];
            }
            $manage_bm = $all['manage_bm'] ?? '';
            if ($manage_bm != '' && $manage_bm != '""') {
                $bmidList = Utils::getChildSonBranchs($manage_bm);
            } else {
                $bmidList = Utils::getWorkerChildSonBranchs(Worker::find($worker_id));
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参存在问题，请联系管理员确认问题', 'WC015');
        }

        try {
            if (count($bmidList) == 0) {
                return LMReturn::Error('没有查看员工的权限', 'WC008');
            }
            $worker_list = Worker::select(
                "worker.*",
                "role.name as role_name",
                "branch.name as bm_name",
                "role.id as role_id",
                "branch.id as branch_id"
            )
                ->with('branchesManage')
                ->leftjoin("worker_role", "worker.id", "=", "worker_role.worker_id")
                ->leftjoin("role", "worker_role.role_id", "=", "role.id")
                ->leftjoin("worker_branch", "worker.id", "=", "worker_branch.worker_id")
                ->leftjoin("branch", "branch.id", "=", "worker_branch.branch_id")
                ->whereIn("branch.id", $bmidList)
                ->where($where)
                ->whereIn('user_status', [0, 1])
                ->orderBy("branch.id")
                ->orderByDesc("worker.update_time")
                ->paginate($pageSize);
            $worker_list = json_decode(json_encode($worker_list), true);
            foreach ($worker_list['data'] as $key => $value) {
                $worker_list['data'][$key]['sex'] = $value['sex'] == 1 ? '男' : '女';
                if (count($value['branches_manage']) > 0) {
                    $manage_list = [];
                    $manage_name_list = [];
                    foreach ($value['branches_manage'] as $manage) {
                        $manage_list[] = $manage['id'];
                        $manage_name_list[] = $manage['name'];
                    }
                    $worker_list['data'][$key]['manage_bm'] = $manage_list;
                    $worker_list['data'][$key]['manage_bm_name'] = implode('/', $manage_name_list);
                } else {
                    $worker_list['data'][$key]['manage_bm'] = [];
                    $worker_list['data'][$key]['manage_bm_name'] = '无权限';
                }
                $worker_list['data'][$key]['age'] = isset($value['birthday']) ? CommonFun::birthday($value['birthday']) : '';
                unset($worker_list['data'][$key]['branches_manage']);
            }
            return LMReturn::Success($worker_list, '查询成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('查询存在问题，请联系管理员确认问题', 'WC007');
        }
    }

    //员工删除(假删除)
    public function WorkerDelete(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], 'WC005');
            }
            //接收前端传递过来的值
            $all = $request->all();
            $worker_id = $all['id'];
        } catch (\Throwable $th) {
            //throw $th;
        }
        try {
            $worker = Worker::find($worker_id);
            if ($worker->account_status == 3) {
                return LMReturn::Error('员工不存在', 'WC010');
            }
            $worker->account_status = 3;
            $phoneNum = $worker->phoneNum ?? '无';
            $contactNum = $worker->contactNum ?? '无';
            $worker->remark = $worker->remark . '-系统：员工已删除,删除时间：' . date("Y-m-d H:i:s", time()) . ',原账号为：' . $phoneNum . ',原联系方式为：' . $contactNum;
            $worker->phoneNum = NULL;
            $worker->contactNum = NULL;
            $worker->save();
            return LMReturn::Success($worker, '员工已删除');
        } catch (\Throwable $th) {
            return LMReturn::Error('删除失败，请联系技术支持', 'WC004');
        }
    }

    //返回登录员工的信息
    public function GetWorkerInfo(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], 'WC006');
        }
        //通过在Token里面获取到的数据的信息，来查询到这个用户的信息
        $info = json_decode(Worker::where("id", $tokenInfo['worker_id'])->first(), true);
        return LMReturn::Success($info);
    }

    /**
     * @description: 员工离职
     * @param {Request} $request
     * @return {*}
     */
    public function workerDimission(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        if (isset($all['dimission_worker_id'])) {
            $dimission_worker_id = $all['dimission_worker_id'];
        } else {
            return LMReturn::Error('请问谁要离职？', 'WC001');
        }
        if (isset($all['transfer_worker_id'])) {
            $transfer_worker_id = $all['transfer_worker_id'];
        } else {
            return LMReturn::Error('请问要交接给谁呢？', 'WC003');
        }
        try {
            $worker = Worker::where('id', $dimission_worker_id)->first();
            $worker->user_status = 0; //1是在职 0是离职
            $worker->outTime = date("Y-m-d H:i:s", time());
            $worker->save();
            $userList = User::where('worker_id', $dimission_worker_id)->get();
            // print($userList);
            foreach ($userList as $user) { //交接用户，添加历史记录
                $user->worker_id = $transfer_worker_id;
                $user->save();
                $user_worker = new UserWorker();
                $user_worker->old_worker_id = $dimission_worker_id;
                $user_worker->worker_id = $transfer_worker_id;
                $user_worker->user_id = $user->id;
                $user_worker->state = '1'; // 1离职交接
                $user_worker->remark = '离职交接';
                $user_worker->save();
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('网络问题，交接失败', 'WC002');
        }
        return LMReturn::Success($userList, '交接成功，员工已离职');
    }

    /**
     * @description: 重置员工密码
     * @param {Request} $request
     * @return {*}
     */
    public function resetWorkerPassword(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $all = $request->all();
            $worker_id = $all['worker_id'];
            $record_worker_id = $tokenInfo['worker_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参错误', 'WC012');
        }

        try {
            $worker = Worker::find($worker_id);
            $pass_data = Utils::passwordSystem('1', $worker);
            $worker->password = $pass_data['password'];
            $this->resetPasswordRecord($worker_id, $record_worker_id);
            $worker->save();
            return LMReturn::Success($worker, $pass_data['message']);
        } catch (\Throwable $th) {
            return LMReturn::Error('重置密码失败', 'WC013');
        }
    }

    /**
     * @description: 新增重置密码记录
     * @param {Request} $request
     * @return {*}
     */
    public function resetPasswordRecord($worker_id, $record_worker_id)
    {
        SystemRecord::create([
            'title' => '重置密码操作',
            'type' => '1',
            'content' => '重置密码操作',
            'worker_id' => $worker_id,
            'record_worker_id' => $record_worker_id,
        ]);
    }
}
